import { defineConfig, devices } from '@playwright/test';

/**
 * @see https://playwright.dev/docs/test-configuration
 */
export default defineConfig({
  // 测试目录
  testDir: './tests/e2e',
  
  // 并行运行测试
  fullyParallel: true,
  
  // 在 CI 中失败时不重试
  forbidOnly: !!process.env.CI,
  
  // 在 CI 中重试失败的测试
  retries: process.env.CI ? 2 : 0,
  
  // 并发工作进程数
  workers: process.env.CI ? 1 : undefined,
  
  // 报告器配置
  reporter: [
    ['html', { outputFolder: 'test-results/playwright-report' }],
    ['json', { outputFile: 'test-results/playwright-results.json' }],
    ['junit', { outputFile: 'test-results/playwright-results.xml' }],
    process.env.CI ? ['github'] : ['list'],
  ],
  
  // 全局设置
  use: {
    // 基础 URL
    baseURL: 'http://localhost:1420',
    
    // 追踪配置
    trace: 'on-first-retry',
    
    // 截图配置
    screenshot: 'only-on-failure',
    
    // 视频录制
    video: 'retain-on-failure',
    
    // 超时设置
    actionTimeout: 10000,
    navigationTimeout: 30000,
  },

  // 项目配置
  projects: [
    {
      name: 'electron',
      use: {
        ...devices['Desktop Chrome'],
        // Electron 特定配置
        launchOptions: {
          executablePath: process.env.ELECTRON_PATH || undefined,
        },
      },
      testMatch: '**/*.spec.ts',
    },
    
    // 可以添加更多浏览器配置用于 Web 版本测试
    {
      name: 'chromium',
      use: { ...devices['Desktop Chrome'] },
      testIgnore: '**/*.spec.ts', // 忽略 Electron 特定测试
    },

    {
      name: 'firefox',
      use: { ...devices['Desktop Firefox'] },
      testIgnore: '**/*.spec.ts',
    },

    {
      name: 'webkit',
      use: { ...devices['Desktop Safari'] },
      testIgnore: '**/*.spec.ts',
    },

    // 移动设备测试
    {
      name: 'Mobile Chrome',
      use: { ...devices['Pixel 5'] },
      testIgnore: '**/*.spec.ts',
    },
    
    {
      name: 'Mobile Safari',
      use: { ...devices['iPhone 12'] },
      testIgnore: '**/*.spec.ts',
    },
  ],

  // 本地开发服务器配置
  webServer: process.env.CI ? undefined : {
    command: 'npm run dev',
    url: 'http://localhost:1420',
    reuseExistingServer: !process.env.CI,
    timeout: 120000,
  },
  
  // 输出目录
  outputDir: 'test-results/playwright-artifacts',
  
  // 全局设置和拆卸
  globalSetup: require.resolve('./tests/e2e/global-setup.ts'),
  globalTeardown: require.resolve('./tests/e2e/global-teardown.ts'),
  
  // 测试超时
  timeout: 60000,
  
  // 期望超时
  expect: {
    timeout: 10000,
  },
  
  // 元数据
  metadata: {
    'test-type': 'e2e',
    'app-version': process.env.npm_package_version || '1.0.0',
  },
});
